<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MeetingSeriesImgVO } from '#/api/meeting/series/model';

import { computed, ref } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { Button, Image, Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  meetingSeriesImgPage,
  meetingSeriesImgRemove,
  meetingSeriesImgUpdateStatus,
} from '#/api/meeting/series';
import { TableSwitch } from '#/components/table';
import fallbackImageBase64 from '#/views/system/oss/fallback-image.txt?raw';

import { columns } from './data';
import seriesImgModal from './series-img-modal.vue';

// const emit = defineEmits<{ reload: [] }>();
const currSeriesId = ref<any>(null);
const currName = ref<any>('');
const title = computed(() => {
  return `${currName.value} - 系列图片列表`;
});
const { hasAccessByCodes } = useAccess();
const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[85%]',
  onClosed: handleClosed,
  // onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.lock(true);
    //
    const { id, name } = drawerApi.getData() as {
      id?: number | string;
      name?: string;
    };
    currSeriesId.value = id;
    currName.value = name;

    drawerApi.lock(false);
  },
});

async function handleClosed() {
  currSeriesId.value = null;
  currName.value = '';
}

// 图片table
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await meetingSeriesImgPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          seriesId: currSeriesId.value,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'meeting-series-img-index',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});

// 新增编辑
const [SeriesImgModal, modalApi] = useVbenModal({
  connectedComponent: seriesImgModal,
});

function handleAdd() {
  modalApi.setData({ seriesId: currSeriesId.value });
  modalApi.open();
}

async function handleEdit(row: MeetingSeriesImgVO) {
  modalApi.setData({ id: row.id, seriesId: currSeriesId.value });
  modalApi.open();
}

async function handleDelete(row: MeetingSeriesImgVO) {
  await meetingSeriesImgRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: MeetingSeriesImgVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await meetingSeriesImgRemove(ids);
      await tableApi.query();
    },
  });
}

async function statusUpdate(row: MeetingSeriesImgVO) {
  const data = {
    id: row.id,
    status: row.status,
  };
  await meetingSeriesImgUpdateStatus(data);
}
</script>

<template>
  <BasicDrawer :footer="false" title="系列图片管理">
    <BasicTable :table-title="title">
      <template #toolbar-tools>
        <Space>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['meeting:seriesImg:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['meeting:seriesImg:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #mobileImgOssId="{ row }">
        <Image
          v-if="row.mobileImgOssId"
          :key="row.mobileImgOssId"
          :src="row.mobileImgUrl"
          width="150px"
          :fallback="fallbackImageBase64"
        >
          <template #placeholder>
            <div class="flex size-full items-center justify-center">
              <Spin />
            </div>
          </template>
        </Image>
      </template>
      <template #pcImgOssId="{ row }">
        <Image
          v-if="row.pcImgOssId"
          :key="row.pcImgOssId"
          :src="row.pcImgUrl"
          width="150px"
          :fallback="fallbackImageBase64"
        >
          <template #placeholder>
            <div class="flex size-full items-center justify-center">
              <Spin />
            </div>
          </template>
        </Image>
      </template>
      <template #thumbnailOssId="{ row }">
        <Image
          v-if="row.thumbnailOssId"
          :key="row.thumbnailOssId"
          :src="row.thumbnailUrl"
          width="150px"
          :fallback="fallbackImageBase64"
        >
          <template #placeholder>
            <div class="flex size-full items-center justify-center">
              <Spin />
            </div>
          </template>
        </Image>
      </template>
      <template #jumpUrl="{ row }">
        <Button
          v-if="row.jumpUrl"
          type="link"
          :href="row.jumpUrl"
          target="_blank"
        >
          {{ row.jumpUrl }}
        </Button>
      </template>
      <template #status="{ row }">
        <TableSwitch
          v-model:value="row.status"
          :api="() => statusUpdate(row)"
          :disabled="!hasAccessByCodes(['meeting:seriesImg:edit'])"
          @reload="tableApi.query()"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['meeting:seriesImg:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['meeting:seriesImg:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <SeriesImgModal @reload="tableApi.query()" />
  </BasicDrawer>
</template>
